package com.wc5818.common;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;

/*
pom.xml
<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-core</artifactId>
  <version>4.0.3</version>
</dependency>
*/
public class SendSms {
	public static long sendcode(String phone) {

		if (phone.trim().length() != 11) {
			return 0;
		}

		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4FuqfPsBYt5vh98kwWxz",
				"U3Z2mFWjrrcUx5Z617TcXLiw0QKeQ9");
		IAcsClient client = new DefaultAcsClient(profile);
		long random = BaseTools.getRandomNum(6);

		CommonRequest request = new CommonRequest();
		request.setMethod(MethodType.POST);
		request.setDomain("dysmsapi.aliyuncs.com");
		request.setVersion("2017-05-25");
		request.setAction("SendSms");
		request.putQueryParameter("RegionId", "cn-hangzhou");
		request.putQueryParameter("PhoneNumbers", phone);
		request.putQueryParameter("SignName", "万车俱乐部");
		request.putQueryParameter("TemplateCode", "SMS_182385027");
		request.putQueryParameter("TemplateParam", "{\"code\":\"" + random + "\"}");
		try {
			CommonResponse response = client.getCommonResponse(request);
			System.out.print(response.getData());
			/****
			 * {"Message":"OK","RequestId":"34641134-482B-4F5C-B23A-4F7E608F92BB","BizId":"915323278627839922^0","Code":"OK"}
			 */

			Gson gson = new Gson();
			SendSMSMESS sm = gson.fromJson(response.getData(), SendSMSMESS.class);
			if (!"ok".equals(sm.getCode().toLowerCase()) || !"ok".equals(sm.getMessage().toLowerCase())) {
				return 0;
			}

			return random;
		} catch (ServerException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		}

		return random;

	}
}

class SendSMSMESS {

	private String Message;

	public String getMessage() {
		return Message;
	}

	public void setMessage(String message) {
		Message = message;
	}

	public String getRequestId() {
		return RequestId;
	}

	public void setRequestId(String requestId) {
		RequestId = requestId;
	}

	public String getBizId() {
		return BizId;
	}

	public void setBizId(String bizId) {
		BizId = bizId;
	}

	public String getCode() {
		return Code;
	}

	public void setCode(String code) {
		Code = code;
	}

	private String RequestId;
	private String BizId;
	private String Code;

}
